<template>
  <div class="home">
    <div class="jumbotron jumbotron-fluid">
      <div class="container">
        <h1 class="display-4">Welcome to MovieStream</h1>
        <p class="lead">Watch your favorite movies online anytime, anywhere.</p>
      </div>
    </div>
    
    <div class="container">
      <div class="search-container">
        <div class="row">
          <div class="col-md-6">
            <input 
              type="text" 
              v-model="searchTerm" 
              @keyup.enter="performSearch" 
              class="form-control form-control-lg" 
              placeholder="Search movies by title..."
            >
          </div>
          <div class="col-md-3">
            <select v-model="selectedGenre" @change="performFilter" class="form-control form-control-lg">
              <option value="">All Genres</option>
              <option v-for="genre in genres" :key="genre" :value="genre">{{ genre }}</option>
            </select>
          </div>
          <div class="col-md-3">
            <button @click="performSearch" class="btn btn-primary btn-lg btn-block">Search</button>
          </div>
        </div>
      </div>
      
      <div v-if="loading" class="text-center my-5">
        <div class="spinner-border text-primary" role="status">
          <span class="sr-only">Loading...</span>
        </div>
        <p class="mt-2">Loading movies...</p>
      </div>
      
      <div v-else-if="error" class="alert alert-danger text-center" role="alert">
        <h4 class="alert-heading">Error loading movies</h4>
        <p>{{ error }}</p>
        <button @click="fetchMovies" class="btn btn-primary">Try Again</button>
      </div>
      
      <div v-else>
        <h2 class="mb-4">
          {{ searchTerm ? `Search Results (${totalElements})` : 
             selectedGenre ? `${selectedGenre} Movies (${totalElements})` : 
             `Featured Movies (${totalElements})` }}
        </h2>
        
        <div v-if="movies.length === 0" class="text-center my-5">
          <div class="display-4 text-muted">🎬</div>
          <h3 class="mt-3">No movies found</h3>
          <p class="lead">
            {{ searchTerm ? 'Try a different search term' : 
               selectedGenre ? 'No movies in this genre' : 
               'No movies available' }}
          </p>
          <button v-if="searchTerm || selectedGenre" @click="clearFilters" class="btn btn-primary">Clear Filters</button>
        </div>
        
        <div v-else>
          <div class="row">
            <div class="col-lg-3 col-md-4 col-sm-6 mb-4" v-for="movie in movies" :key="movie.id">
              <div class="card h-100">
                <img :src="movie.coverImageUrl || 'https://via.placeholder.com/300x400?text=No+Image'" 
                     class="card-img-top" 
                     :alt="movie.title"
                     style="height: 300px; object-fit: cover;">
                <div class="card-body d-flex flex-column">
                  <h5 class="card-title">{{ movie.title }} ({{ movie.year }})</h5>
                  <p class="card-text flex-grow-1">{{ truncateText(movie.description, 100) }}</p>
                  <div class="mb-2">
                    <span class="badge badge-primary">{{ movie.genre }}</span>
                    <span class="badge badge-success ml-1">{{ movie.rating }}/10</span>
                  </div>
                  <div class="mb-2">
                    <small class="text-muted">{{ formatDuration(movie.duration) }}</small>
                  </div>
                  <div class="mt-auto">
                    <router-link :to="'/movie/' + movie.id" class="btn btn-primary btn-sm">
                      Watch Now
                    </router-link>
                    <button @click="toggleFavorite(movie.id)" class="btn btn-sm ml-2" 
                            :class="isFavorite(movie.id) ? 'btn-danger' : 'btn-outline-danger'">
                      <span v-if="isFavorite(movie.id)">❤️</span>
                      <span v-else>🤍</span>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页组件 -->
          <nav aria-label="Movie pagination" v-if="totalPages > 1">
            <ul class="pagination justify-content-center">
              <li class="page-item" :class="{ disabled: currentPage === 0 }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage - 1)">Previous</a>
              </li>
              
              <li v-for="page in pageNumbers" :key="page" class="page-item" :class="{ active: currentPage === page-1 }">
                <a class="page-link" href="#" @click.prevent="changePage(page-1)">{{ page }}</a>
              </li>
              
              <li class="page-item" :class="{ disabled: currentPage === totalPages - 1 }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage + 1)">Next</a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import store from '../store'

export default {
  name: 'Home',
  data() {
    return {
      movies: [],
      genres: [],
      loading: true,
      searchTerm: '',
      selectedGenre: '',
      error: null,
      
      // 分页相关数据
      currentPage: 0,
      totalPages: 0,
      totalElements: 0,
      pageSize: 8
    }
  },
  computed: {
    pageNumbers() {
      const pages = []
      const start = Math.max(1, this.currentPage - 1)
      const end = Math.min(this.totalPages, this.currentPage + 3)
      
      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      
      return pages
    }
  },
  mounted() {
    this.fetchMovies()
    this.fetchGenres()
  },
  methods: {
    fetchMovies() {
      this.loading = true
      this.error = null
      axios.get(`http://localhost:8080/api/movies/page?page=${this.currentPage}&size=${this.pageSize}`)
        .then(response => {
          this.movies = response.data.content
          this.totalPages = response.data.totalPages
          this.totalElements = response.data.totalElements
          this.currentPage = response.data.number
          this.loading = false
        })
        .catch(error => {
          console.error('Error fetching movies:', error)
          this.error = 'Failed to load movies. Please try again later.'
          this.loading = false
        })
    },
    fetchGenres() {
      axios.get('http://localhost:8080/api/movies/genres')
        .then(response => {
          this.genres = response.data
        })
        .catch(error => {
          console.error('Error fetching genres:', error)
        })
    },
    performSearch() {
      // 重置分页
      this.currentPage = 0
      
      if (this.searchTerm.trim() === '') {
        this.fetchMovies()
        return
      }
      
      this.loading = true
      this.error = null
      axios.get(`http://localhost:8080/api/movies/search/page?title=${this.searchTerm}&page=${this.currentPage}&size=${this.pageSize}`)
        .then(response => {
          this.movies = response.data.content
          this.totalPages = response.data.totalPages
          this.totalElements = response.data.totalElements
          this.currentPage = response.data.number
          this.loading = false
        })
        .catch(error => {
          console.error('Error searching movies:', error)
          this.error = 'Failed to search movies. Please try again later.'
          this.loading = false
        })
    },
    performFilter() {
      // 重置分页
      this.currentPage = 0
      
      if (this.selectedGenre === '') {
        this.fetchMovies()
        return
      }
      
      this.loading = true
      this.error = null
      axios.get(`http://localhost:8080/api/movies/genre/${this.selectedGenre}/page?page=${this.currentPage}&size=${this.pageSize}`)
        .then(response => {
          this.movies = response.data.content
          this.totalPages = response.data.totalPages
          this.totalElements = response.data.totalElements
          this.currentPage = response.data.number
          this.loading = false
        })
        .catch(error => {
          console.error('Error filtering movies:', error)
          this.error = 'Failed to filter movies. Please try again later.'
          this.loading = false
        })
    },
    clearFilters() {
      this.searchTerm = ''
      this.selectedGenre = ''
      this.currentPage = 0
      this.fetchMovies()
    },
    changePage(page) {
      if (page < 0 || page >= this.totalPages) {
        return
      }
      
      this.currentPage = page
      
      if (this.searchTerm) {
        this.performSearch()
      } else if (this.selectedGenre) {
        this.performFilter()
      } else {
        this.fetchMovies()
      }
    },
    truncateText(text, maxLength) {
      if (text.length <= maxLength) {
        return text
      }
      return text.substr(0, maxLength) + '...'
    },
    formatDuration(minutes) {
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      if (hours > 0) {
        return `${hours}h ${mins}m`
      }
      return `${mins}m`
    },
    // 收藏功能相关方法
    toggleFavorite(movieId) {
      if (store.isFavorite(movieId)) {
        store.removeFavorite(movieId)
      } else {
        store.addFavorite(movieId)
      }
    },
    isFavorite(movieId) {
      return store.isFavorite(movieId)
    }
  }
}
</script>

<style scoped>
/* 样式已移至全局样式文件 */
</style>